<template>
  <el-dialog
    title="芯片名称统计表导入导出"
    :visible.sync="circuitGenerationModuleDialogVisible"
    width="27%"
  >
    <el-form
      :model="formData"
      :rules="formRules"
    >
      <el-form-item
        label="芯片名称统计表"
        prop="circuitGenerationChipModelList"
        style="margin-left: 50px;"
      >
        <el-upload
          ref="chipDefinitionFiles"
          class="upload-demo"
          :accept="'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel'"
          action="#"
          :limit="1"
          style="margin-right: 10px"
          :before-upload="beforeUpload"
        >
          <div slot="tip" class="el-upload__tip">
            只能上传xlsx或xls格式的文件，且文件不超过 20 MB
          </div>
          <el-button size="small" plain>
            上传文件
            <i class="el-icon-upload el-icon--right" />
          </el-button>
        </el-upload>
        <transition-group name="el-fade-in-linear" tag="div">
          <div
            v-for="file in formData.circuitGenerationChipModelList"
            :key="file.uid"
            :file="file"
            :disabled="true"
          >
            <i class="el-icon-document" />
            {{ file.name }}
            <el-button
              slot="action"
              type="text"
              icon="el-icon-delete"
              @click="beforeRemove(file)"
            >
              <i class="el-icon-close" />
            </el-button>
          </div>
        </transition-group>
      </el-form-item>
    </el-form>
    <div style="display: flex; justify-content: flex-end; margin-top: 20px; overflow: hidden;">
      <el-tooltip class="item" effect="dark" content="增量导入会自动识别重复数据,仅增加新数据" placement="bottom">
        <el-button type="primary" @click="handleClick('addImport')">增量导入</el-button>
      </el-tooltip>
      <el-tooltip class="item" effect="dark" content="警告！此操作将会删除系统中原有的数据" placement="bottom">
        <el-button type="primary" @click="handleClick('overWriteImport')">覆盖式导入</el-button>
      </el-tooltip>
      <el-button type="primary" @click="handleClick('export')">导出芯片名称统计表</el-button>
      <el-button style="margin-left: 10px" @click="circuitGenerationModuleDialogVisible=false">关闭</el-button>
    </div>

  </el-dialog>
</template>

<script>

import {
  circuitGenerationModuleChip,
  exportCircuitGenerationModuleChip, importChipModuleTargetFromExcelAll,
  importChipModuleTargetFromExcelIncrement
} from '@/api/project-management'
import defaultSettings from '@/settings'
import { generateUUID, postMessage, receivedMessage } from '@/utils/index'
import { fileDownload } from '@/utils/download'

export default {
  name: 'circuitGenerationChipModel',
  data() {
    return {
      file: {},
      circuitGenerationModuleDialogVisible: false,
      fullscreenLoading: false,
      formData: {
        circuitGenerationChipModelList: []
      },
      formRules: {
        circuitGenerationChipModelList: [
          { required: true, message: '请上传电路生成模块型号名称表', trigger: 'blur' }
        ]
      },
      loading: null,
      importExcelId: generateUUID(),
      exportCircuitGenerationModuleChipRequestId: generateUUID()
    }
  },
  watch: {
    circuitGenerationModuleDialogVisible(val) {
      if (!val) {
        this.formData.circuitGenerationChipModelList = []
        this.file = {}
      }
    }
  },
  mounted() {
    receivedMessage(this.dataHandle)
  },
  methods: {
    dataHandle(result) {
      let self = this
      let e = defaultSettings.isWPF ? result : { data: JSON.parse(result) }
      if (e.data.webInfo.requestId === self.importExcelId) {
        self.afterImport(e.data.response)
      } else if (e.data.webInfo.requestId === self.exportCircuitGenerationModuleChipRequestId) {
        let res = e.data.response
        if (res.success) {
          var bytes = new Uint8Array(
            window
              .atob(res.data)
              .split('')
              .map(function (c) {
                return c.charCodeAt(0)
              })
          )
          res.data = bytes
          fileDownload(res)
        }
        self.loading.close()
        self.circuitGenerationModuleDialogVisible = false
      }
    },
    handleClick(type) {
      switch (type) {
        case 'overWriteImport':
          this.overWriteImportWarn()
          break
        case 'addImport':
          this.handleImport('addImport')
          break
        case 'export':
          this.handleExport()
          break
      }
    },
    is() {
      this.circuitGenerationModuleDialogVisible = true
    },
    beforeUpload(file) {
      const isExcel = file.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' || file.type === 'application/vnd.ms-excel'
      if (!isExcel) {
        this.$message.error('只能上传 Excel 文件')
        return false
      }
      const isLt20M = file.size / 1024 / 1024 < 20
      if (!isLt20M) {
        this.$message.error('上传文件大小不能超过 20MB!')
        return false
      }
      this.formData.circuitGenerationChipModelList = []
      this.file = file
      this.formData.circuitGenerationChipModelList.push(file)
      this.$nextTick(() => {
      })
      return false
    },
    beforeRemove() {
      this.formData.circuitGenerationChipModelList = []
      this.file = {}
    },
    handleImport(module) {
      let data = new FormData()
      data.append('file', this.file)
      if (this.file === undefined || this.file?.name === undefined) {
        this.$message.error('请先上传文件')
        return false
      }
      if (this.file.name.indexOf('xlsx') === -1 && this.file.name.indexOf('xls') === -1) {
        this.$message.error('请上传xlsx或xls格式的文件')
        return false
      }
      let requireFile = this.file
      if (module === 'addImport') {
        this.loading = this.openFullScreenLoading('导入中')
        if (defaultSettings.isWPF || defaultSettings.isCEF) {
          let self = this;
          let reader = new FileReader() // new一个FileReader实例
          reader.readAsDataURL(this.file) // 读取为base64
          reader.onloadend = function () { // 当读取完成时
            let message = self.getMessagePushParam('/circuitGenerationModuleChip/importChipModuleTargetFromExcelIncrement', self.importExcelId, {
              fileName: requireFile.name,
              fileContent: reader.result.split(',')[1]
            })
            postMessage(message)
          }
        } else {
          importChipModuleTargetFromExcelIncrement(data).then((res) => {
            this.afterImport(res)
          }).catch((res) => {
            this.loading.close()
            this.$message.error(res.message)
          })
        }
      }
      else if (module === 'overWriteImport') {
        this.loading = this.openFullScreenLoading('导入中')
        if (defaultSettings.isWPF || defaultSettings.isCEF) {
          let self = this;
          let reader = new FileReader() // new一个FileReader实例
          reader.readAsDataURL(this.file) // 读取为base64
          reader.onloadend = function () { // 当读取完成时
            let message = self.getMessagePushParam('/circuitGenerationModuleChip/importChipModuleTargetFromExcelAll', self.importExcelId, {
              fileName: requireFile.name,
              fileContent: reader.result.split(',')[1]
            })
            postMessage(message)
          }
        } else {
          importChipModuleTargetFromExcelAll(data).then((res) => {
            this.afterImport(res)
          }).catch((res) => {
            this.loading.close()
            this.$message.error(res)
          })
        }
      }
    },
    afterImport(res){
      this.loading.close();
      if (res.success) {
        this.$message({
          message: '导入成功',
          type: 'success'
        })
        this.circuitGenerationModuleDialogVisible = false
      } else {
        this.$message.error(res.message)
      }
    },
    handleExport() {
      if (defaultSettings.isWPF || defaultSettings.isCEF) {
        this.exportCircuitGenerationModuleChipRequestId = generateUUID()
        let self = this
        let message = this.getMessagePushParam('/circuitGenerationModuleChip/exportExcel', self.exportCircuitGenerationModuleChipRequestId, {})
        postMessage(message)
      } else {
        this.loading = this.openFullScreenLoading('导出预处理中');
        exportCircuitGenerationModuleChip().then((response) => {
          this.loading.close();
          if (!response) {
            this.$message.error('导出失败,请联系管理员')
          } else {
            fileDownload(response)
          }
        });
      }
    },
    getMessagePushParam(apiUrl, webInfo, data) {
      return {
        RequestUrl: process.env.VUE_APP_URL + apiUrl,
        RequestMethod: 'POST',
        Headers: {
          contentType: 'application/json'
        },
        QueryParameter: {},
        RequestBody: data,
        WebInfo: {
          requestId: webInfo
        }
      }
    },
    fileDownload(response) {
      const blob = new Blob([response], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8' });
      const link = document.createElement('a');
      link.href = window.URL.createObjectURL(blob);
      // 文件名从请求头获取
      let fileName = response.headers['content-disposition'].split(';')[1].split('=')[1];
      link.download = decodeURI(fileName);
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link); // 下载完成移除元素
      this.$message({
        message: '导出成功',
        type: 'success'
      })
    },
    openFullScreenLoading(text) {
      const loading = this.$loading({
        lock: true,
        text: text || '加载中',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      });
      return loading
    },
    overWriteImportWarn() {
      if (this.file === undefined || this.file?.name === undefined) {
        this.$message.error('请先上传文件')
        return false
      }
      this.$confirm('此操作将会删除系统中原有的数据信息，请问您是否继续？如仅需新增芯片名称信息，请使用增量导入功能。', '警告', {
        confirmButtonText: '继续',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.handleImport('overWriteImport')
      });
    }
  }
}
</script>

<style scoped lang="less">

</style>
